<!DOCTYPE html>
<html>

<head>
    <title>TalkingChan</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link href="https://cdn.bootcss.com/open-iconic/1.1.1/font/css/open-iconic-bootstrap.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/emojionearea/3.4.1/emojionearea.min.css" rel="stylesheet">
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery.textcomplete/1.8.4/jquery.textcomplete.min.js"></script>
    <script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
    <script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
    <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
    <script src="https://cdn.bootcss.com/emojionearea/3.4.1/emojionearea.min.js"></script>
    <script>
        
        var username = "";
        var roomid = "";
        var socket = io.connect("ws://" + location.hostname + ":3001");
        var timerRefreshClients = null;
        var lastClientUpdateTime = null;
        var resetTime=5;
        var msgStack={};
        var earea=null;
        var timerClear = setInterval(() => {
            ClearMsgIn()
        }, 1000*30);
        var NowId=0;
        function GetMsgId(){
            return NowId++;
        }
        function ClearMsgIn(){
            console.log("开始清理...");
            var now=new Date().getTime() - resetTime * 60 * 1000;
            $(".msg").each(function(index,item){
                var time=$(item).data("time");
                console.log("清理比较",time,now);
                if(time<now){
                    console.log("清理:"+time);
                    $(".msg[data-time='" + time + "']").remove();
                }else{
                    
                    console.log("不清理:" + time);
                }
            });
        }
        function SendMsg() {
            var msg = earea[0].emojioneArea.getText();//$("#div_msg_out").val();// $("#div_msg_out").html();
            msg= msg.replace(/\n/g,"<br/>");
            console.log('send ' + msg);
            // $("#div_msg_in").append(
            //     '<div class="alert alert-primary msg" role="alert">'
            //     +msg
            //     +'</div>'
            // );
            //$("#div_msg_out").html('');
            //$("#div_msg_out").val('');
            var c=setTimeout(function(){
                earea[0].emojioneArea.setText('');
                clearTimeout(c);
            },0);
            if (msg) {
                var obj = {
                    'username': username,
                    'content': msg,
                    'roomid': roomid
                }
                socket.emit('message', obj);
            }
        }
        function ResetTime(){
            resetTime=parseInt($("#select_time").val().replace("分钟",""));
        }
        function RefreshClients() {
            var now = new Date();
            var ts = now - lastClientUpdateTime;
            if (ts > 1000 * 6) {
                clearInterval(timerRefreshClients);
                $("#span_status").html("您已下线，请点击重新登陆");
            } else {
                var userInfo = {
                    'roomid': roomid,
                    'username': username
                };
                //连接socket后端服务器
                //通知用户有用户登录
                socket.emit('clients', userInfo);
            }
        }
        function SetUsers(clients) {
            console.log('set users:', clients);
            var usr = "";
            for (var i = 0; i < clients.length; i++) {
                usr = usr + '<button type="button" style="margin:3px" class="btn btn-success"><span class="oi oi-person"></span>' + clients[i].name + '</button>';
            }
            $("#div_users").html(
                usr
            );
        }
        function div_msg_out_onkeypress(){
            
            if (event.keyCode == 13) {
                if (event.shiftKey) {

                } else {
                    SendMsg();
                    return false;
                }
            }
        }
        $(document).ready(function () {
            Notification.requestPermission();
            earea=$("#div_msg_out").emojioneArea(
                { 
                    tones: false,
                    events:{
                        keypress:function(jq,event){
                            console.log(event);
                            if (event.keyCode == 13) {
                                if (event.shiftKey) {

                                } else {
                                    SendMsg();
                                    return false;
                                }
                            }
                        }
                    }
                }
            );
            $("#div_msg_out").html('');
            //$("#div_msg_in").emojioneArea({ tones: false, hidePickerOnBlur:true});
            // $("#div_msg_out").keydown(function (event) {
            //     if (event.keyCode == 13) {
            //         if (event.shiftKey) {

            //         } else {
            //             SendMsg();
            //             return false;
            //         }
            //     }
            // });
            $("#button_login").click(function () {

                username = $("#username").val();
                roomid = $("#roomid").val();
                var userInfo = {
                    'roomid': roomid,
                    'username': username
                };
                //连接socket后端服务器
                //通知用户有用户登录
                socket.emit('login', userInfo);
                lastClientUpdateTime = new Date();
                clearInterval(timerRefreshClients);
                timerRefreshClients = setInterval(function () {
                    try {
                        RefreshClients();
                    } catch (ex) { }
                }, 3000);
            });
            $("#button_logout").click(function () {
                console.log("准备退出聊天室");
                var userInfo = {
                    'roomid': roomid,
                    'username': username
                };
                //连接socket后端服务器
                //通知用户有用户登录
                socket.emit('logout', userInfo);
                clearInterval(timerRefreshClients);
                $("#span_status").html("已退出");
            });

            //监听新用户登录
            socket.on('login', function (o) {
                $("#span_status").html("本聊天室共" + o.length + "个人");
                console.log(o);
                lastClientUpdateTime = new Date();
                //updateMsg(o, 'login');
            });
            //监听新用户登录
            socket.on('clients', function (o) {
                SetUsers(o);
                $("#span_status").html("本聊天室共" + o.length + "个人");
                console.log(o);
                lastClientUpdateTime = new Date();
                //updateMsg(o, 'login');
            });
            //监听用户退出
            socket.on('logout', function (o) {
                $("#span_status").html("本聊天室共" + o.length + "个人");
                //updateMsg(o, 'logout');
            });
            //发送消息
            socket.on('message', function (obj) {
                console.log("收到消息:", obj);
                var msgtime= new Date().getTime();
                if (obj.username == username) {
                    var MsgHtml = '<div data-time="'+ msgtime+'" class="msg alert alert-primary msg" role="alert">'
                        + '<span style="color:white">' + obj.username + '&nbsp;&nbsp;'+new Date().toTimeString()+'</span>'
                        + '<div>' + obj.content + '</div>'
                        + '</div>';
                } else {
                    var MsgHtml = '<div data-time="' + msgtime +'" class="msg alert alert-success msg" role="alert">'
                        + '<span style="color:pink">' + obj.username + '&nbsp;&nbsp;' + new Date().toTimeString() +'</span>'
                        + '<div>' + obj.content + '</div>'
                        + '</div>';
                }
                
                $("#div_msg_in").append(
                    MsgHtml
                );
                $('#div_msg_in').scrollTop(99999);
                if(document.visibilityState!='visible'){
                    document.title="[新消息~]";
                    var options = {
                        body: "你有一条来自的 "+obj.username+" 的新消息"
                    }
                    var n = new Notification("TalkingChan", options);
                }else{
                    document.title = "TalkingChan";
                }
            });
        });

    </script>
</head>

<body>
    <div>
        <div class="card" style="width: 52rem;">
            <div class="card-body">
                <div>
                    <div>
                        <p>
                            <button class="btn btn-primary" type="button" data-toggle="collapse"
                                data-target="#collapseExample" aria-expanded="true" aria-controls="collapseExample">
                                切换房间信息是否展示
                            </button>
                        </p>
                        <div class="collapse show" id="collapseExample">
                            <div class="card card-body">
                                <form>
                                    <div class="col-auto">
                                        <label class="sr-only" for="roomid">暗号</label>
                                        <div class="input-group mb-2">
                                            <div class="input-group-prepend">
                                                <div class="input-group-text">暗号</div>
                                            </div>
                                            <input type="text" class="form-control" id="roomid"
                                                placeholder="两人的暗号一致，则可以对话">
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <label class="sr-only" for="username">用户名</label>
                                        <div class="input-group mb-2">
                                            <div class="input-group-prepend">
                                                <div class="input-group-text">用户名</div>
                                            </div>
                                            <input type="text" class="form-control" id="username"
                                                placeholder="对方会看到你的用户名">
                                        </div>
                                    </div>
                                    <div class="col-auto" style="text-align: right;padding: 1rem">
                                        <span id="span_status"></span>
                                        <select value="5" id="select_time" onchange="ResetTime()">
                                            <option>1</option>
                                            <option>2</option>
                                            <option>3</option>
                                            <option>5</option>
                                            <option>10</option>
                                        </select>分钟自动清除
                                        <button class="btn btn-success" type="button" id="button_login">登陆</button>
                                        <button class="btn btn-error" type="button" id="button_logout">登出</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    <div id="div_users">

                    </div>
                    <div style="margin-top:1rem">
                        <div class="card" style="width: 50rem;">
                            <div class="card-body">
                                <div id="div_msg_in" style="height:30rem;overflow: auto"></div>
                            </div>
                        </div>
                    </div>
                    <!-- <div id="div_msg_out" contenteditable="true" onkeypress="div_msg_out_onkeypress"
                        style="height: 3rem;border: 1px solid rgba(0,0,0,.125);border-radius: .25rem;margin-top:1rem;overflow-y: scroll;">
                    </div> -->
                    <textarea id="div_msg_out" type="text"></textarea>
                    <div style="text-align: right;margin-right:3rem;margin-top:1rem">
                        <button onclick="SendMsg()" type="button" class="btn btn-primary">发送</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>